import React, { Component, useEffect } from 'react'
import { Table, Space, Modal, Form, Input, Popconfirm, message, Button } from 'antd'
import XLSX from 'xlsx'
import { getUsers, modifyUser, deleteUser, addUser } from '../../api/users'

const { Search } = Input

// 定义一个函数组件
const CollectionCreateForm = ({
  visible,
  onCreate,
  onCancel,
  currentEdit,
  isEdit
}) => {
  const [form] = Form.useForm()

  // HOOK，相当于 class 组件中的 componentDidMount()/componentDidUpdate()/componentWillUnmount()
  useEffect(() => {
    form.setFieldsValue(currentEdit)
  }, [currentEdit, form])

  return (
    <Modal
      visible={visible}
      title={ isEdit ? '修改' : '添加' }
      okText={ isEdit ? '修改' : '添加' }
      cancelText="取消"
      forceRender
      onCancel={onCancel}
      onOk={() => {
        form
          .validateFields()
          .then(values => {
            onCreate(values)
          })
          .catch(info => {
            console.log('Validate Failed:', info)
          })
      }}
    >
      <Form
        form={form}
        layout="vertical"
        name="form_in_modal"
      >
        <Form.Item
          name="id"
          label="编号"
          hidden
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="username"
          label="用户名"
          rules={[{ required: true, message: '必须填写用户名' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="name"
          label="姓名"
          rules={[{ required: true, message: '必须填写姓名' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="email"
          label="电子邮箱"
        >
          <Input />
        </Form.Item>
        <Form.Item
          name="phone"
          label="电话"
        >
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  )
}

// 默认表单中填写的用户数据
const defaultUser = {
  id: null,
  name: null,
  username: null,
  email: null,
  phone: null
}

export default class Users extends Component {

  state = {
    users: [], // 保存所有用户的数据,
    editFormVisible: false, // 编辑用户信息的对话框是否可见
    currentEdit: {}, // 当前编辑的用户对象
    isEdit: false, // 对对话框实现标记，添加或修改，false表示添加, true表示修改
  }

  // 表格中列的定义
  columns = [
    {
      title: '编号',
      dataIndex: 'id',
      key: 'id'
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      render: text => <a href="/">{text}</a>,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username'
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email'
    },
    {
      title: '地址',
      dataIndex: 'address',
      key: 'address',
      render: address => <span>{ address && address.street }</span>
    },
    {
      title: '公司',
      dataIndex: 'company',
      key: 'company',
      render: company => <span>{ company && company.name }</span>
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => ( // record 就是渲染表格行时数组中的某个元素对象
        <Space size="middle">
          <a href="/" onClick={e => {
            e.preventDefault()
            this.setVisible(true)
            this.setState({
              currentEdit: record,
              isEdit: true
            })
          }}>编辑</a>
          <Popconfirm
            title="是否确认删除？"
            onConfirm={ () => this.confirm(record) }
            onCancel={ this.cancel }
            okText="确定"
            cancelText="取消"
          >
            <a href="/">删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ]

  /**
   * 组件挂载后，ajax 请求用户数据
   */
  componentDidMount() {
    getUsers().then(res => {
      this.setState({
        users: res
      })
    }).catch(err => console.log(err))
  }

  /**
   * 在编辑对话框中当点击确定按钮时的回调函数
   * 判断当前是修改还是添加操作
   * @param {*} values 
   */
  onCreate = values => {
    console.log('Received values of form: ', values)
    if (this.state.isEdit) { // 修改
      modifyUser(values).then(res => {
        // console.log('修改响应：', res)

        // 将修改成功的用户信息替换掉 state 中 users 数组对应的用户
        const newUsers = this.state.users.map(user => {
          if (user.id === res.id) {
            return {
              ...user,
              ...res
            }
          }
          return user
        })
        this.setState({
          users: newUsers
        })

        // 修改成功，则关闭对话框
        this.setVisible(false)
      }).catch(e => console.log('修改异常：', e))
    } else { // 添加
      addUser(values).then(res => {
        console.log(res)
        // 将添加成功的用户信息保存到 users 数组中
        const newUsers = [
          res,
          ...this.state.users
        ]
        this.setState({
          users: newUsers
        })

        // 添加成功，则关闭对话框
        this.setVisible(false)
      }).catch(e => console.log('添加异常：', e))
    }
  }

  /**
   * 设置编辑对话框是否可见
   * @param {*} visible 
   */
  setVisible = visible => {
    this.setState({
      editFormVisible: visible
    })
  }

  /**
   * 确定删除
   */
  confirm = userinfo => {
    deleteUser(userinfo).then(res => {
      console.log(res)
      // 删除成功，将当前删除行从表格中移除
      const newUsers = this.state.users.filter(user => user.id !== userinfo.id)
      this.setState({
        users: newUsers
      })
      // 提示删除成功
      message.success('删除成功');
    }).catch(e => console.log('删除异常：', e))
  }

  /**
   * 取消删除
   */
  cancel = e => {
    console.log(e);
    message.error('Click on No');
  }

  // 导出excel文件
  exportFile = () => {
    /* convert state to workbook */
    const data = []
    data.push(Object.keys(this.state.users[0]))
    this.state.users.forEach(user => {
      data.push(Object.values(user))
    })
		const ws = XLSX.utils.aoa_to_sheet(data); // 工作表
		const wb = XLSX.utils.book_new(); // 工作簿
		XLSX.utils.book_append_sheet(wb, ws, "SheetJS"); // 将工作表添加到工作簿中
		/* generate XLSX file and send to client */
		XLSX.writeFile(wb, "sheetjs.xlsx") // 写入文件
	}

  render() {
    return (
      <>
        <Search
          placeholder="请输入取消的姓名"
          onSearch={value => console.log(value)}
          style={{ width: 200 }}
        />

        <Button type="primary" onClick={ () => {
          this.setVisible(true)
          this.setState({
            isEdit: false,
            currentEdit: defaultUser
          })
        } }>添加新用户</Button>

        <Button
          type="primary"
          style={{marginLeft: 10}}
          onClick={ this.exportFile }
        >
          导出excel
        </Button>

        <Table
          columns={this.columns}
          dataSource={ this.state.users }
          rowKey="id"
          pagination={{
            // pageSize: 3,
            // total: 10
          }}
        />

        <CollectionCreateForm
          visible={ this.state.editFormVisible }
          onCreate={this.onCreate}
          onCancel={() => {
            this.setVisible(false)
          }}
          currentEdit={ this.state.currentEdit }
          isEdit={ this.state.isEdit }
        />
      </>
    )
  }
}
